package com.android.clinic.app.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.android.clinic.app.ClinicApplication;
import com.android.clinic.app.R;
import com.android.clinic.app.ui.video.CallActivity;
import com.android.clinic.app.utils.AppManager;
import com.android.clinic.app.utils.Constants;
import com.gyf.barlibrary.ImmersionBar;
import com.jiongbull.jlog.JLog;

import java.util.ArrayList;
import java.util.List;

import io.agora.AgoraAPI;
import io.agora.rtc.RtcEngine;

public class MainActivity extends AppCompatActivity implements OnCheckedChangeListener {

    private RadioGroup mRadioGroup;

    private FragmentManager mFragmentManager;
    private Fragment mFragment;
    private List<Fragment> mFragmentList = new ArrayList<>();
    private long lastBackTime = 0;

    public ImmersionBar mImmersionBar;
    protected final int REQUEST_CODE = 0x01;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AppManager.getAppManager().addActivity(this);
        mRadioGroup = (RadioGroup) findViewById(R.id.radio_group);
        mRadioGroup.setOnCheckedChangeListener(this);
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.init();
        initFragment();
    }

    private void initFragment() {
        mFragmentManager = getSupportFragmentManager();
        mFragment = new Fragment();

        mFragmentList.clear();
        mFragmentList.add(new HomeFragment());
        mFragmentList.add(new MessageFragment());
        mFragmentList.add(new MineFragment());

        ((RadioButton) mRadioGroup.getChildAt(0)).setChecked(true);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        String tag = mRadioGroup.findViewById(checkedId).getTag().toString();
        switchFragmentStack(Integer.parseInt(tag));
        switch (tag) {
            case "0":
            case "2":
                mImmersionBar.statusBarColorTransform(R.color.colorPrimaryDark)
                        .barAlpha(0f)
                        .init();
                break;
            case "1":
                mImmersionBar.statusBarDarkFont(true, 0.2f).init();
                break;
        }
    }

    private void switchFragmentStack(int index) {
        FragmentTransaction ft = mFragmentManager.beginTransaction();
        Fragment fragment = mFragmentList.get(index);
        if (mFragment != fragment) {
            if (!fragment.isAdded()) {
                ft.hide(mFragment).add(R.id.container, fragment,
                        fragment.getClass().getName());
            } else {
                ft.hide(mFragment).show(fragment);
            }
            mFragment = fragment;
        }
        ft.commit();
    }

    /**
     * 获取当前Fragment
     *
     * @return
     */
    public Fragment getVisibleFragment() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        List<Fragment> fragments = fragmentManager.getFragments();
        for (Fragment fragment : fragments) {
            if (fragment != null && fragment.isVisible())
                return fragment;
        }
        return null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null == ClinicApplication.getUserInfo()) {
            ((RadioButton) mRadioGroup.getChildAt(0)).setChecked(true);
        }
        JLog.e("onActivityResult requestCode: " + requestCode + " resultCode: " + resultCode);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            if (data != null && data.getStringExtra("result").equals("finish")) {
                finish();
            }
        }
    }

    @Override
    public void onBackPressed() {
        long currentBackTime = System.currentTimeMillis();
        if (currentBackTime - lastBackTime > 2000) {
            Toast.makeText(this, "再按一次返回键退出", Toast.LENGTH_SHORT).show();
            lastBackTime = currentBackTime;
        } else {
            super.onBackPressed();
            AppManager.getAppManager().finishAllActivity();
            System.exit(0);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        addCallBack();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RtcEngine.destroy();
    }

    /**
     * 声网SDK回调处理
     */
    private void addCallBack() {
        JLog.e("addCallback enter." );
        ClinicApplication.getInstance().getAngoraAPI().callbackSet(new AgoraAPI.CallBack(){

            /**
             * 登录成功回调
             * @param uid
             * @param fd
             */
            @Override
            public void onLoginSuccess(int uid, int fd) {
                JLog.e("登录成功回调...");
            }

            /**
             * 退出登录回调
             * @param encode
             */
            @Override
            public void onLogout(int encode) {
                JLog.e("退出登录回调...");
            }

            /**
             * 登录失败回调
             * @param encode
             */
            @Override
            public void onLoginFailed(int encode) {
                JLog.e("登录失败回调...");

            }

            /**
             * 收到呼叫邀请回调
             * @param channelID
             * @param account
             * @param uid
             * @param extra
             */
            @Override
            public void onInviteReceived(String channelID, String account, int uid, String extra) {
                JLog.e("收到远端的呼叫邀请回调...");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(MainActivity.this, CallActivity.class);
                        intent.putExtra("account", account);
                        intent.putExtra("channelName", channelID);
                        intent.putExtra("extra", extra);
                        intent.putExtra("type", Constants.CALL_IN);
                        startActivityForResult(intent, REQUEST_CODE);
                    }
                });
            }
        });
    }

}
